<?php

require_once 'Zend/Mail/Transport/Smtp.php';
require_once 'Zend/Mail.php';

/**
 * This model contains all methods to deal with actions on the user account (registration, 
 * login, logout, password forgotten, and view of the public profile page).
 */
class Model_Users {
    
    /**
     * Prevents MySQL Injection
     * @param type $input - input to be prevented from MySQL Injection
     * @return type - returns safe input
     * @author Matej Kollar
     */
    public function preventMySqlInjection($input) {
        $safeInput = ""; 
        $safeInput = mysql_real_escape_string($input);
        return $safeInput;
    } 
    
    /**
     * Prevents Cross Site Scripting
     * @param type $input - input to be prevented from XSS
     * @return type - returns safe input
     * @author Matej Kollar
     */
    public function preventXSS($input) {
        $safeInput = "";      
        $safeInput = htmlspecialchars($input, ENT_QUOTES, 'UTF-8');
        return $safeInput;
        }
    
        /**
         *Returns true if a string ends with a certain suffix
         * @param type $input - The string that is controlled by the function
         * @param type $suffix - the suffix $input should end with
         * @return type - returns true if $string ends with $suffix
         * @author Dominik Imsirovic
         */
        public function endsWith($string, $suffix ){
            return strcmp( substr( $string, strlen($string)-strlen($suffix)),$suffix)==0;
        }

    /**
     * Insert a new user into the database
     * @param array $data - the basic information about this new user
     * @return string - the confirmation code of this new user
     * @author Christophe Sourisse
     */
    public function insert(array $data) {
        
        // Prevent SQLi
        $data['username'] = self::preventMySqlInjection($data['username']);
        $data['email'] = self::preventMySqlInjection($data['email']);
        $data['password'] = self::preventMySqlInjection($data['password']);
        
        // Prevent XSS
        $data['username'] = self::preventXSS($data['username']);
        $data['email'] = self::preventXSS($data['email']);
        $data['password'] = self::preventXSS($data['password']);
        
        // Get the database connection
        $db = Zend_Registry::get("my_db");
        
        // Generate the confirmation code
        $cC = self::generateConfirmationCode();
        
        // Prepare the row to insert
        $new = array(
            'userName' => $data['username'],
            'emailAddress' => $data['email'],
            'password' => $data['password'],
            'confirmationCode' => $cC,
            'isActivated' => 0
        );
        
        // Finally insert it and return the confirmation code
        $db->insert('users', $new);
        return $cC;
    }

    /**
     * Generates confirmation code
     * @param type $long - the length of the confirmation code (by default 7)
     * @return string - confirmation code
     * @author Christophe Sourisse
     */
    public function generateConfirmationCode($long = 7) {
        $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        $res = '';
        
        // Generate one by one the random characters of the confirmation code
        for ($i = 0; $i < $long; $i++) {
            $idx = rand(0, strlen($chars) - 1);
            $random = substr($chars, $idx, 1);
            $res = $res . $random;
        }
        
        // and finally return it
        return $res;
    }

    /**
     * Sends confirmation email
     * @param type $to - email address
     * @param type $confirmationCode - confirmation code
     * @author Matej Kollar 
     */
    public function sendConfirmationMail($to, $confirmationCode) {

//        echo 'To: ' . $to . "<br>";
//        echo 'Confirmation Code: ' . $confirmationCode . "<br>";   
        
        $safeTo = self::preventXSS($to);

        $subject = "What's up? - Account Activation";
        $body = "Welcome on the What's up!\n\n" .
                "Please follow the link below to activate your What's Up Account:\n" .
                "http://localhost/WhatsUpProject/public/user/registration?confirmationCode=" .
                $confirmationCode . "\n\n" .
                "Your What's Up Team";
        $config = array(
            'auth' => 'login',
            'username' => 'whatsupwhatsup44@gmail.com',
            'password' => 'abs2381abs2381',
            'ssl' => 'ssl' // 'tls' not working, 'ssl' works fine 
        );
        $transport = new Zend_Mail_Transport_Smtp('smtp.gmail.com', $config);
        $mail = new Zend_Mail();
        $mail->setBodyText($body);
        $mail->setFrom('whatsupwhatsup44', 'What\'s Up Team');
        $mail->addTo($safeTo, $safeTo);
        $mail->setSubject($subject);
        $mail->send($transport);
    }

    /**
     * Unlocks the user after following the link in Account Activation Email
     * @param type $cC - confirmation code
     * @author Matej Kollar 
     */
    public function unlock($cC) {
        $db = Zend_Registry::get("my_db");
        $stmt = $db->query("UPDATE users SET isActivated = '1' WHERE confirmationCode = '$cC'");
        $stmt->execute();
    }

    
    public function splitUsersIDString($users) {
        return preg_split("#,#", $users);
    }

    public function getUsers($usersIDs) {
       $users_array = array();
       if (strlen($usersIDs) > 0) {
       $usersIDs_array = self::splitUsersIDString($usersIDs); 
          foreach ($usersIDs_array as $userID) {
              $users_array[] = self::getUser($userID);
          }
       }
       return $users_array;
    }

    public function getUser($userID) {
        $db = Zend_Registry::get("my_db");
        $sql = 'SELECT * FROM users WHERE id=?';
        $result = $db->fetchAll($sql, $userID);
        return $result[0];
    }

    /**
     * Creates user session
     * @param type $email - email address of the user
     * @param type $password - password of the user
     * @return type - retuns true, if the user is active (successfuly registered) user
     * @author Matej Kollar 
     */
    public function createSession($email, $password) {
//        echo 'Email: ' . $email . "<br>";
//        echo 'Password: ' . $password . "<br>";       

        $session = Zend_Registry::get("my_session_namespace");
        $db = Zend_Registry::get("my_db");
        
        $safeEmail = self::preventMySqlInjection($email);
        $safePassword = self::preventMySqlInjection($password);

        $stmt = $db->query("SELECT * FROM users WHERE emailAddress = '$safeEmail' AND password = '$safePassword'");
        $result = $stmt->fetch();

//        echo 'id: ' . $result['id'] . "<br>";
//        echo 'emailAddress: ' . $result['emailAddress'] . "<br>";
//        echo 'password: ' . $result['password'] . "<br>";
//        echo 'confirmationCode: ' . $result['confirmationCode'] . "<br>";
//        echo 'isActivated: ' . $result['isActivated'] . "<br>";
//        echo 'topics: ' . $result['topics'] . "<br>";  

        $isActivated = $result['isActivated'];

        if ($isActivated) {

            if (!isset($session->user)) {
                $session->user = $result;
            }

            // $session->user["emailAddress"];
//            if (!isset($session->id)) {
//                $session->id = $result['id'];
//            }
//
//            if (!isset($session->emailAddress)) {
//                $session->emailAddress = $result['emailAddress'];
//            }
//
//            if (!isset($session->password)) {
//                $session->password = $result['password'];
//            }
//
//            if (!isset($session->confirmationCode)) {
//                $session->confirmationCode = $result['confirmationCode'];
//            }
//
//            if (!isset($session->isActivated)) {
//                $session->isActivated = $result['isActivated'];
//            }
//
//            if (!isset($session->topics)) {
//                $session->topics = $result['topics'];
//            }
//        echo 'id: ' . $session->id . "<br>";
//        echo 'emailAddress: ' . $session->emailAddress . "<br>";
//        echo 'password: ' . $session->password . "<br>";
//        echo 'confirmationCode: ' . $session->confirmationCode . "<br>";
//        echo 'isActivated: ' . $session->isActivated . "<br>";
//        echo 'topics: ' . $session->topics . "<br>"; 

            return true;
        } else {
            return false;
        }
    }

    /**
     * Destroys user session
     * @author Matej Kollar
     */
    public function destroySession() {
        Zend_Session::namespaceUnset('my_session_namespace');
        Zend_Session::expireSessionCookie();
        Zend_Session::stop();
        // Zend_Session::destroy(false); // this method does not work (Bug in ZF)
    }

    /**
     * Sends user password to the user
     * @param type $to - user email address
     * @return type - if successful, returns true, otherweise returns false
     * @author Matej Kollar
     */
    public function sendPasswordMail($to) {
//        echo 'To: ' . $to . "<br>";

        $db = Zend_Registry::get("my_db");
        
        $safeTo = self::preventMySqlInjection($to);
        
        $stmt = $db->query("SELECT * FROM users WHERE emailAddress = '$safeTo'");
        $result = $stmt->fetch();

//        echo 'id: ' . $result['id'] . "<br>";
//        echo 'emailAddress: ' . $result['emailAddress'] . "<br>";
//        echo 'password: ' . $result['password'] . "<br>";
//        echo 'confirmationCode: ' . $result['confirmationCode'] . "<br>";
//        echo 'isActivated: ' . $result['isActivated'] . "<br>";
//        echo 'topics: ' . $result['topics'] . "<br>";         
//        if ($result == false) {
//            echo 'No result was found!' . "<br>";
//        }
//        if ($result != false) {
//            echo 'Result was found!' . "<br>";
//        }

        if ($result != false) {
            $subject = "What's up? - Your Password";
            $body = "Dear What's up User,\n\n" .
                    "here is your password: " . $result['password'] . "\n\n" .
                    "Your What's Up Team";
            $config = array(
                'auth' => 'login',
                'username' => 'whatsupwhatsup44@gmail.com',
                'password' => 'abs2381abs2381',
                'ssl' => 'ssl' // 'tls' not working, 'ssl' works fine 
            );
            $transport = new Zend_Mail_Transport_Smtp('smtp.gmail.com', $config);
            $mail = new Zend_Mail();
            $mail->setBodyText($body);
            $mail->setFrom('whatsupwhatsup44', 'What\'s Up Team');
            $mail->addTo($safeTo, $safeTo);
            $mail->setSubject($subject);
            $mail->send($transport);
            return true;
        } else {
            return false;
        }
    }
    
    /**
     * Get a user represented by his username.
     * @param string $avatar - the user's surname
     * @return array - the expected user
     * @author Christophe Sourisse
     */
    public function getUserBySurname($avatar) {
       $db = Zend_Registry::get("my_db");
       $sql = 'SELECT * FROM users WHERE userName=?';
       $result = $db->fetchAll($sql, $avatar);
       return $result[0];
    }
    
    /**
     * Method to insert a new topic into the database
     * @param type $data - contains name and description of the new topic
     * @author Dominik Imsirovic
     */
    public function insertTopic($data){
        
          $db = Zend_Registry::get("my_db");
          $session = Zend_Registry::get("my_session_namespace");
          
            
          
        $new = array(
            'userName' => self::preventMySqlInjection($data["topicName"]),
           'name'=>self::preventMySqlInjection($session->user["userName"]),
            'emailAddress'=>"topic",
            'password'=>"topic",
            'description' => self::preventMySqlInjection($data["topicDescription"]),
            'isTopic' =>1,
            'isActivated' => 1
        );
        
          /*$new = array(
            'userName' => self::preventMySqlInjection($data["topicName"]),
           'name'=>self::preventMySqlInjection($session->user["userName"]),
            'description' => self::preventMySqlInjection($data["topicDescription"]),
            'isTopic' =>1,
            'isActivated' => 1
        ); */
        
        $db->insert('users', $new); 
        
    }

}
